<template>
  <div class="wrapper">
    <div class="back" @click="goBack">
      <img src="@/assets/images/back_arrow.png" class="back" alt="header" />
    </div>
    <VueFlow
      :nodes="nodes"
      :edges="edges"
      :fit-view-on-init="true"
      :zoom-on-scroll="false"
      :pan-on-drag="false"
      @node-click="onNodeClick"
      class="graph"
    >
      <!-- bind your custom node type to a component by using slots, slot names are always `node-<type>` -->
      <template #node-special="specialNodeProps">
        <SpecialNode v-bind="specialNodeProps" />
      </template>

      <!-- bind your custom edge type to a component by using slots, slot names are always `edge-<type>` -->
      <template #edge-special="specialEdgeProps">
        <SpecialEdge v-bind="specialEdgeProps" />
      </template>
      <!-- <Background></Background> -->
    </VueFlow>
  </div>
</template>
<script setup>
import { ref, onMounted, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { VueFlow, Position } from '@vue-flow/core';
import { useSubjectSelectStore } from '@/store/subjectSelect';

import { Background } from '@vue-flow/background';
// these components are only shown as examples of how to use a custom node or edge
// you can find many examples of how to create these custom components in the examples page of the docs
import SpecialNode from './components/SpecialNode.vue';
import SpecialEdge from './components/SpecialEdge.vue';
import { getGraphNode } from '@/api/subjectSelect';

const router = useRouter();
const store = useSubjectSelectStore();

// these are our nodes
// const nodes = ref([
//   // an input node, specified by using `type: 'input'`
//   {
//     id: '1-1',
//     type: 'input',
//     position: { x: 0, y: 200 },
//     // all nodes can have a data object containing any data you want to pass to the node
//     // a label can property can be used for default nodes
//     data: { label: '物化生' },
//     sourcePosition: Position.Right,
//     style: { background: 'blue', color: '#fff' },
//   },

//   // default node, you can omit `type: 'default'` as it's the fallback type
//   {
//     id: '2-1',
//     position: { x: 350, y: 0 },
//     data: { label: '计算机技术与工程' },
//     sourcePosition: Position.Right,
//     targetPosition: Position.Left,
//   },

//   // An output node, specified by using `type: 'output'`
//   {
//     id: '2-2',
//     // type: 'special',
//     position: { x: 350, y: 200 },
//     data: { label: '数据分析' },
//     sourcePosition: Position.Right,
//     targetPosition: Position.Left,
//   },
//   {
//     id: '2-3',
//     // type: 'special',
//     position: { x: 350, y: 400 },
//     data: { label: '电子信息工程' },
//     sourcePosition: Position.Right,
//     targetPosition: Position.Left,
//   },
//   // default node, you can omit `type: 'default'` as it's the fallback type
//   {
//     id: '3-1',
//     position: { x: 600, y: 0 },
//     data: { label: 'python工程师' },
//     sourcePosition: Position.Right,
//     targetPosition: Position.Left,
//   },

//   // An output node, specified by using `type: 'output'`
//   {
//     id: '3-2',
//     // type: 'special',
//     position: { x: 600, y: 200 },
//     data: { label: 'python工程师' },
//     sourcePosition: Position.Right,
//     targetPosition: Position.Left,
//   },
//   {
//     id: '3-3',
//     // type: 'special',
//     position: { x: 600, y: 400 },
//     data: { label: 'python工程师' },
//     sourcePosition: Position.Right,
//     targetPosition: Position.Left,
//   },

//   // this is a custom node
//   // we set it by using a custom type name we choose, in this example `special`
//   // the name can be freely chosen, there are no restrictions as long as it's a string
//   {
//     id: '4-1',
//     type: 'output', // <-- this is the custom node type name
//     position: { x: 900, y: 200 },
//     data: {
//       label: '人工智能产业',
//       hello: 'world',
//     },
//     targetPosition: Position.Left,
//     style: { background: '#ff0072', color: '#fff' },
//   },
// ]);

// const edges = ref([
//   {
//     id: '1',
//     source: '1-1',
//     target: '2-1',
//     animated: true,
//     style: {
//       stroke: '#0b6eff',
//     },
//   },
//   {
//     id: '2',
//     source: '1-1',
//     target: '2-2',
//     animated: true,
//     style: {
//       stroke: '#0b6eff',
//     },
//   },
//   {
//     id: '3',
//     source: '1-1',
//     target: '2-3',
//     animated: true,
//     style: {
//       stroke: '#0b6eff',
//     },
//   },
//   {
//     id: '4',
//     source: '2-1',
//     target: '3-1',
//     animated: true,
//     style: {
//       stroke: 'green',
//     },
//   },
//   {
//     id: '5',
//     source: '2-2',
//     target: '3-2',
//     animated: true,
//     style: {
//       stroke: 'green',
//     },
//   },
//   {
//     id: '6',
//     source: '2-3',
//     target: '3-3',
//     animated: true,
//     style: {
//       stroke: 'green',
//     },
//   },
//   {
//     id: '7',
//     source: '3-1',
//     target: '4-1',
//     animated: true,
//     style: {
//       stroke: 'red',
//     },
//   },
//   {
//     id: '8',
//     source: '3-2',
//     target: '4-1',
//     animated: true,
//     style: {
//       stroke: 'red',
//     },
//   },
//   {
//     id: '9',
//     source: '3-3',
//     target: '4-1',
//     animated: true,
//     style: {
//       stroke: 'red',
//     },
//   },
// ]);

const subjects = ref(['物化生']);
const majors = ref(['计算机技术与工程', '数学与应用数学', '电子信息工程']);
const positions = ref(['python工程师', '电子工程师', '软件工程师']);
const industries = ref(['人工智能产业']);

// 拼接ID的函数
function concatIds(subjectsArray) {
  // 提取所有ID并转换为数字
  const ids = subjectsArray.map((subject) => parseInt(subject.id));
  // 对ID进行排序（升序）
  ids.sort((a, b) => a - b);
  // 用逗号拼接成字符串
  return ids.join(',');
}

const getGraphNodeFn = async () => {
  const params = {
    // regionId: '440000',
    // recordYear: '2025',
    // limitNum:'3', // 几条线段
    searchAllowSubject: concatIds(store.intelligenceSubject),
    industryId: store.intelligenceIndustry.id,
  };
  const res = await getGraphNode(params);
  if (res.code == 200) {
    subjects.value = res.data.subjectNameList;
    industries.value = res.data.industryNameList;
    majors.value = res.data.positionTagNameList;
    positions.value = res.data.positionNameList;

    subjectNodes.value = getSubjectNodes(subjects.value);
    majorNodes.value = getMajorNodes(majors.value);
    positionNodes.value = getPositions(positions.value);
    industryNodes.value = getIndustries(industries.value);

    nodes.value = [
      ...subjectNodes.value,
      ...majorNodes.value,
      ...positionNodes.value,
      ...industryNodes.value,
    ];

    edges.value = [
      ...generateEdgesFromNodesOneToMulti(
        subjectNodes.value,
        majorNodes.value,
        '#0b6eff'
      ),
      ...generateEdgesFromNodesMultiToMulti(
        majorNodes.value,
        positionNodes.value,
        'green'
      ),
      ...generateEdgesFromNodesMultiToOne(
        positionNodes.value,
        industryNodes.value,
        'red'
      ),
    ];
    console.log('nodes.value----', nodes.value);
    localStorage.setItem('nodes', JSON.stringify(nodes.value));
    localStorage.setItem('edges', JSON.stringify(edges.value));
  }
};

const onNodeClick = ({ event, node }) => {
  console.log(node);
  if (node.id['0'] == '1') {
  }
  if (node.id['0'] == '2') {
    console.log('node', node);
    router.push({
      name: 'MajorDetail',
      query: {
        positionTagId: node.data.id || '10635',
        tagName: node.data.label || '智慧农业',
        cateType: node.data.cateType || 30,
      },
    });
    localStorage.setItem('graphNodes', '1');
  }
  if (node.id['0'] == '3') {
    router.push({
      name: 'PositionDetail',
      query: {
        positionId: node.data.id || '118118',
        positionIdName: node.data.label || '餐厅店长',
      },
    });
    localStorage.setItem('graphNodes', '1');
  }
  if (node.id['0'] == '4') {
    router.push({
      name: 'IndustryDetail',
      query: {
        code: node.data.id,
        industryType: 10,
        name: encodeURIComponent(node.data.label),
      },
    });
    localStorage.setItem('graphNodes', '1');
  }
};

const getSubjectNodes = (subjects) => {
  return subjects.map((subject, index) => ({
    id: `1-${index + 1}`,
    type: 'input',
    position: { x: 50, y: 200 * (index + 2.5) },
    data: { label: subject.title, id: subject.id },
    sourcePosition: Position.Right,
    style: { background: '#0B6EFF', color: '#fff', borderColor: '#0B6EFF' },
  }));
};
const getMajorNodes = (majors) => {
  console.log('majors', majors);
  return majors.map((major, index) => ({
    id: `2-${index + 1}`,
    position: { x: 300 + index * 40, y: `${100 * (index + 2)}` },
    data: { label: major.title, id: major.id },
    sourcePosition: Position.Right,
    targetPosition: Position.Left,
    style: { background: '#0EAE7A', color: '#fff', borderColor: '#0EAE7A' },
  }));
};
const getPositions = (positions) => {
  return positions.map((position, index) => ({
    id: `3-${index + 1}`,
    position: { x: 600 + index * 40, y: `${110 * (index + 1)}` },
    data: { label: position.title, id: position.id },
    sourcePosition: Position.Right,
    targetPosition: Position.Left,
    style: { background: '#7C2AD6', color: '#fff', borderColor: '#7C2AD6' },
  }));
};
const getIndustries = (industries) => {
  return industries.map((industry, index) => ({
    id: `4-${index + 1}`,
    type: 'output',
    position: { x: 900, y: `0` },
    data: { label: industry.title, id: industry.id },
    targetPosition: Position.Left,
    style: { background: '#D62A7F', color: '#fff', borderColor: '#D62A7F' },
  }));
};

const id = ref(1);

function generateEdgesFromNodesOneToMulti(
  sourceNodes,
  targetNodes,
  color = '#0B6EFF'
) {
  const edges = [];
  sourceNodes.forEach((source) => {
    targetNodes.forEach((target) => {
      edges.push({
        id: id.value.toString(),
        source: sourceNodes[0].id,
        target: target.id,
        animated: true,
        style: { stroke: color },
      });
      id.value++;
    });
  });
  return edges;
}

function generateEdgesFromNodesMultiToMulti(
  sourceNodes,
  targetNodes,
  color = '#0B6EFF'
) {
  const edges = [];
  sourceNodes.forEach((source, index) => {
    edges.push({
      id: id.value.toString(),
      source: sourceNodes[index].id,
      target: targetNodes[index].id,
      animated: true,
      style: { stroke: color },
    });
    id.value++;
  });
  return edges;
}

function generateEdgesFromNodesMultiToOne(
  sourceNodes,
  targetNodes,
  color = '#0b6eff'
) {
  const edges = [];
  sourceNodes.forEach((source, index) => {
    edges.push({
      id: id.value.toString(),
      source: source.id,
      target: targetNodes[0].id,
      animated: true,
      style: { stroke: color },
    });
    id.value++;
  });
  return edges;
}

// const subjectNodes = getSubjectNodes(subjects.value);
// const majorNodes = getMajorNodes(majors.value);
// const positionNodes = getPositions(positions.value);
// const industryNodes = getIndustries(industries.value);
const subjectNodes = ref(null);
const majorNodes = ref(null);
const positionNodes = ref(null);
const industryNodes = ref(null);

// const nodes = ref([
//   ...subjectNodes,
//   ...majorNodes,
//   ...positionNodes,
//   ...industryNodes,
// ]);

const nodes = ref([]);

// const edges = ref([
//   ...generateEdgesFromNodesOneToMulti(subjectNodes, majorNodes, '#0b6eff'),
//   ...generateEdgesFromNodesMultiToMulti(majorNodes, positionNodes, 'green'),
//   ...generateEdgesFromNodesMultiToOne(positionNodes, industryNodes, 'red'),
// ]);
const edges = ref([]);

// console.log(nodes, 'nodes----');
// console.log(edges, 'edges----');

const goBack = () => {
  router.back();
};
onMounted(() => {
  if (localStorage.getItem('graphNodes') == '0') {
    getGraphNodeFn();
  } else {
    nodes.value = JSON.parse(localStorage.getItem('nodes'));
    edges.value = JSON.parse(localStorage.getItem('edges'));
  }
});
onActivated(() => {
  console.log('进入onActivated');
});
</script>

<style lang="scss" scoped>
.wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: space-between;
  .back {
    position: absolute;
    top: 18px;
    left: 18px;
    width: 48px;
    height: 48px;
    z-index: 999;
  }
  .graph {
    background: url('@/assets/images/homeBg.png') no-repeat center center;
    background-size: 100% 100%;
    padding: 0 60px 60px 60px;
    box-sizing: border-box;
    height: 100vh;
    width: 100vw;
    background-color: #f5f5f5;
    background-color: #c2f3ff;
  }
}
</style>
